﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
using System.IO;
using System.Windows.Resources;

namespace SharedCode
{
    public class XapEventArgs : EventArgs
    {
        public UserControl DownloadedContent;
    }
    
    public class Downloader
    {
        #region Local members
        private string assemblyName;
        private string className;
        #endregion

        public event EventHandler<XapEventArgs> XapDownloaded;

        public void LoadPackage(string xap, string asm, string cls)
        {
            assemblyName = asm;
            className = cls;

            Uri address = new Uri(xap, UriKind.RelativeOrAbsolute);
            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(OnCompleted);
            client.OpenReadAsync(address);
        }


        #region Helpers

        private void OnCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (XapDownloaded == null)
                return;

            if (e.Error != null)
                return;

            // Load a particular assembly from XAP
            Assembly a = GetAssemblyFromPackage(assemblyName, e.Result);

            // Get an instance of the XAML object
            object page = a.CreateInstance(className);

            // Fire the event
            XapEventArgs args = new XapEventArgs();
            args.DownloadedContent = page as UserControl;
            XapDownloaded(this, args);
        }

        private Assembly GetAssemblyFromPackage(string assemblyName, Stream xapStream)
        {
            // Local variables
            Uri assemblyUri = null;
            StreamResourceInfo resPackage = null;
            StreamResourceInfo resAssembly = null;
            AssemblyPart part = null;

            // Initialize
            assemblyUri = new Uri(assemblyName, UriKind.Relative);
            resPackage = new StreamResourceInfo(xapStream, null);
            resAssembly = Application.GetResourceStream(
                                      resPackage, assemblyUri);

            // Extract an assembly 
            part = new AssemblyPart();
            Assembly a = part.Load(resAssembly.Stream);
            return a;
        }

        #endregion
    }

}
